package com.lvyq.qrobot.service.impl;

import cn.hutool.core.collection.ListUtil;
import com.lvyq.qrobot.common.UrlConstant;
import com.lvyq.qrobot.entity.*;
import com.lvyq.qrobot.mapper.SysBarrierMapper;
import com.lvyq.qrobot.mapper.SysPropMapper;
import com.lvyq.qrobot.mapper.UserBagMapper;
import com.lvyq.qrobot.mapper.UserMapper;
import com.lvyq.qrobot.model.receive.ReceiveMsg;
import com.lvyq.qrobot.model.send.SendParam;
import com.lvyq.qrobot.service.*;
import com.lvyq.qrobot.util.HttpClientUtil;
import com.lvyq.qrobot.util.LotteryUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author lvyq
 * @version 1.0
 * Create by 2024-06-07 9:45
 */
@Service
public class SysBarrierServiceImpl implements SysBarrierService {

    @Resource
    public UserService userService;

    @Resource
    public SysBarrierMapper sysBarrierMapper;

    @Resource
    public UserMapper userMapper;

    @Resource
    private SysPropMapper sysPropMapper;

    @Resource
    private UserBagMapper userBagMapper;
    @Resource
    public SysBarrierSubService sysBarrierSubService;

    @Resource
    public SysMonsterService sysMonsterService;


    @Resource
    public UserAttributeService userAttributeService;
    @Override
    public void sendMsg(SysOrder sysOrder, SendParam param, ReceiveMsg vo) {
        if (vo.getMessage().equals("关卡")){
            getSysBarrier(sysOrder.content,param,vo);
        }

        //挑战
        if (sysOrder.secType==1){
            challenge(sysOrder.content,param,vo);
        }


    }

    //挑战
    private void challenge(String content, SendParam param, ReceiveMsg vo) {

        String barrierId = vo.message.substring(2,vo.message.length());
        SysBarrier sysBarrier = sysBarrierMapper.selectById(Integer.valueOf(barrierId));
        StringBuffer buffer = new StringBuffer();
        if (sysBarrier!=null){
            //获取子关卡以及怪物
            String finalContent = content;

            Thread thread = new Thread(()->{
                boolean success = true;
                String con = finalContent;
                List<SysBarrierSub> sysBarrierSubs = sysBarrierSubService.getInfoByBarrierId(Integer.valueOf(barrierId));
                UserEntity user = userService.getUser(vo);

                Integer totalExp = 0;
                Integer totalSkill = 0;
                //用户目前总体力
                Integer nowTili = user.tili;
                for (int i = 0; i < sysBarrierSubs.size(); i++) {
                    UserAttribute userAttributeInfo = userAttributeService.getUserAttributeInfo(vo.groupId, vo.userId);
                    //获取对应怪
                    String[] monsters = sysBarrierSubs.get(i).monsters.split("\\*");
                    String monster = monsters[0];
                    Integer num = Integer.valueOf(monsters[1]);
                    System.out.println("monster = " + monster);
                    SysMonster sysMonster = sysMonsterService.getInfoByName(monster);
                    System.out.println("sysMonster = " + sysMonster);
                    if (nowTili<3){
                        buffer.append("挑战失败,体力不足");
                        success=false;
                        break;
                    }else {
                        nowTili=nowTili-3;
                        //计算双方伤害
                        int myDamage = (int) (userAttributeInfo.basicAttack-sysMonster.defense*0.02);
                        int enemyDamage= (int) (sysMonster.basicAttack-userAttributeInfo.defense*0.02);
                        int myHealth = userAttributeInfo.blood;
                        int enemyHealth =sysMonster.blood;
                        int roundsToDefeatMe = (int) Math.ceil((double) myHealth / enemyDamage);
                        System.out.println("我血量:"+myHealth+",伤害："+myDamage+">>敌血量："+enemyHealth+",伤害："+enemyDamage );
                        System.out.println("打败我需要的回合数 = " + roundsToDefeatMe);
                        int roundsToDefeatEnemy = (int) Math.ceil((double) enemyHealth / myDamage);
                        System.out.println("打败敌方需要的回合数 = " + roundsToDefeatEnemy);
                        if (roundsToDefeatMe < roundsToDefeatEnemy) {
                            //敌方获胜
                            buffer.append("悲催啊,你被["+sysMonster.name+"]打败了!\n提升:你的实力太差了~");
                            success=false;
                            break;
                        } else {
                            //随机掉落物品
                            double[] probabilities={0.95,0.02,0.01,0.01,0.01};
                            String[] prizes={"谢谢参与","紫翎羽","翠鸟羽","火凤羽","金翎羽"};

                            String prop = LotteryUtils.calculatePrize(probabilities, prizes);
                            //我方获胜
                            if (prop.equals("谢谢参与")){
                                buffer.append("你打败了["+sysMonster.name+"]\n体力-3\n获得:经验:"+sysMonster.jingyan+",技能点："+sysMonster.skillPoint+"\n");
                            }else {
                                UserBag bag =userBagMapper.selectByName(prop,vo.groupId,vo.userId);
                                if (bag!=null){
                                    bag.setNum(bag.num+1);
                                    userBagMapper.updateById(bag);
                                }else {
                                    bag= new UserBag();
                                    bag.setName(prop);
                                    bag.setNum(1);
                                    bag.setGroupId(vo.groupId);
                                    bag.setUserId(vo.userId);
                                    userBagMapper.insert(bag);
                                }
                                buffer.append("你打败了["+sysMonster.name+"]\n体力-3\n获得:经验:"+sysMonster.jingyan+",技能点："+sysMonster.skillPoint+",物品："+prop+"x1\n");
                            }
                            totalExp=totalExp+sysMonster.jingyan;
                            totalSkill=totalSkill+sysMonster.skillPoint;
                        }
                    }

                }
                user.setSkillPoint(user.skillPoint+totalSkill);
                user.setJingyan(user.jingyan+totalExp);
                user.setTili(nowTili);
                userMapper.updateById(user);
                if (success){
                    buffer.append("恭喜你闯关成功,可以尝试挑战更高级的关卡~");
                }
                con = con.replace("{1}",vo.userId.toString())
                                .replace("{2}",buffer.toString());
                param.setMessage(con);
                HttpClientUtil.doPostJson(UrlConstant.send_group_msg,param);
            });
            thread.start();

        }else{
            content=content.replace("{1}",vo.userId.toString())
                    .replace("{2}","挑战关卡不存在");
            param.setMessage(content);
            HttpClientUtil.doPostJson(UrlConstant.send_group_msg,param);
        }

    }

    /**
     * @description 获取关卡
     * @author lvyq
     * @param[1] content
     * @param[2] param
     * @param[3] vo
     * @throws
     * @time 2024-06-07 10:18
     */
    private void getSysBarrier(String content, SendParam param, ReceiveMsg vo) {
      List<SysBarrier>  list =  sysBarrierMapper.listByType(1);
      StringBuffer buffer = new StringBuffer();
      list.forEach(l->{
          buffer.append(l.sort+"."+l.name+"\n");
      });
      String substring = buffer.substring(0,buffer.length()-1);
      content =content.replace("{1}",substring);
      param.setMessage(content);
      HttpClientUtil.doPostJson(UrlConstant.send_group_msg,param);
    }


    public static void main(String[] args) {
        int myHealth = 100;
        int myDamage = 1;
        int enemyHealth = 20;
        int enemyDamage = 10;
        int roundsToDefeatMe = (int) Math.ceil((double) myHealth / enemyDamage);
        System.out.println("打败我需要的回合数 = " + roundsToDefeatMe);
        int roundsToDefeatEnemy = (int) Math.ceil((double) enemyHealth / myDamage);
        System.out.println("打败敌方需要的回合数 = " + roundsToDefeatEnemy);
        if (roundsToDefeatMe < roundsToDefeatEnemy) {
            System.out.println("敌方能在 " + roundsToDefeatMe + " 轮内击败我方");
        } else {
            System.out.println("我方能在 " + roundsToDefeatEnemy + " 轮内击败敌方");
        }
    }
}
